<template>
  <div class="app-container">
    <div v-if="query.productType === ''">
      <div class="my-code">点击类型查看详情</div>
    </div>
    <div v-else>
      <!--工具栏-->
      <div class="head-container">
        <div v-if="crud.props.searchToggle">
          <!-- 搜索 -->
          <el-input
            v-model="query.productCode"
            clearable
            placeholder="产品型号"
            style="width: 185px"
            class="filter-item"
            @keyup.enter.native="crud.toQuery"
          />
          <el-input
            v-model="query.productName"
            clearable
            placeholder="产品名称"
            style="width: 185px"
            class="filter-item"
            @keyup.enter.native="crud.toQuery"
          />
          <rrOperation :crud="crud" />
        </div>
        <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
        <crudOperation :permission="permission" />
        <!--表单组件-->
        <el-dialog
          :close-on-click-modal="false"
          :before-close="crud.cancelCU"
          :visible.sync="crud.status.cu > 0"
          :title="crud.status.title"
          width="500px"
        >
          <el-form
            ref="form"
            :model="form"
            :rules="rules"
            size="small"
            label-width="80px"
          >
            <el-form-item label="产品类型" prop="productType">
              <el-input
                v-model="form.productType"
                style="width: 370px"
                :disabled="isDisabled"
              />
            </el-form-item>
            <el-form-item label="产品型号" prop="productCode">
              <el-input v-model="form.productCode" :disabled="crud.status.edit" style="width: 370px" />
            </el-form-item>
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" style="width: 370px" />
            </el-form-item>

            <el-form-item label="关联物料" prop="materialCode">
              <el-select
                v-model="form.materialCode"
                style="width: 370px"
                filterable
                placeholder="暂无关联物料"
              >
                <el-option
                  v-for="item in material"
                  :key="item.id"
                  :label="item.materialName"
                  :value="item.materialCode"
                >
                  <span style="float: left">{{ item.materialCode }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{
                    item.materialName
                  }}</span>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="关联产线" prop="lines">
              <el-cascader
                ref="concernLine"
                v-model="form.lines"
                :props="props"
                :options="options"
                style="width: 370px"
                @change="concernLineChange">
              </el-cascader>
            </el-form-item>

            <el-form-item label="描述" prop="remark">
              <el-input v-model="form.remark" :rows="3" type="textarea" style="width: 370px"/>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="text" @click="crud.cancelCU">取消</el-button>
            <el-button
              :loading="crud.status.cu === 2"
              type="primary"
              @click="crud.submitCU"
              >确认</el-button
            >
          </div>
        </el-dialog>
        <!--表格渲染-->
        <el-table
          ref="table"
          v-loading="crud.loading"
          :data="crud.data"
          size="small"
          style="width: 100%"
          @selection-change="crud.selectionChangeHandler"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="productCode" label="产品型号" width="120px" align="center"/>
          <el-table-column prop="productName" label="产品名称" width="150px" align="center"/>
          <el-table-column prop="productType" label="产品类型" width="80px" align="center"/>
          <el-table-column prop="materialCode" label="关联物料" width="150px" align="center"/>
          <el-table-column prop="remark" label="描述" width="250px" align="center"/>
          <el-table-column prop="createBy" label="创建人" width="100px" align="center"/>
          <el-table-column prop="createTime" label="创建时间" width="150px" align="center"/>
          <el-table-column prop="updateBy" label="更新人" width="100px" align="center"/>
          <el-table-column prop="updateTime" label="更新时间" width="150px" align="center"/>
          <el-table-column
            v-if="checkPer(['admin', 'dict:edit', 'dict:del'])"
            label="操作"
            fixed="right"
            width="150px"
            align="center"
          >
            <template slot-scope="scope">
              <udOperation :data="scope.row" :permission="permission" />
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <pagination />
      </div>
    </div>
  </div>
</template>

<script>
import crudProductModel from "@/api/product/productModel";
import crudProductMaterial from "@/api/product/productMaterial";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";
import crudFactoryModel from "@/api/factory/factoryModel";
import crudProductModelLien from "@/api/product/productModelLien";
let id = 0;
const defaultForm = {
  id: null,
  productCode: null,
  productName: null,
  productType: null,
  materialCode: null,
  remark: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  lines : []
};
export default {
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: "产品型号",
      url: "api/productModel",
      idField: "id",
      sort: "id,desc",
      query: { productType: "" },
      optShow: {
        add: true,
        edit: false,
        del: true,
        download: false,
        reset: true,
        import: false,
      },
      queryOnPresenterCreated: false,
      crudMethod: { ...crudProductModel },
    });
  },
  data() {
    return {
      isDisabled: true,
      options: [],
      productType: '',
      props: {
        checkStrictly: true,
        multiple: true,
      },
      permission: {
        add: ["admin", "dict:add"],
        edit: ["admin", "dict:edit"],
        del: ["admin", "dict:del"],
      },
      rules: {
        productCode: [
          { required: true, message: "产品型号不能为空", trigger: "blur" },
        ],
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" },
        ],
        productType: [
          { required: true, message: "产品类型不能为空", trigger: "blur" },
        ],
        materialCode: [
          { required: true, message: "关联物料不能为空", trigger: "blur" },
        ],
        lines: [
          { required: true, message: "关联产线不能为空", trigger: "blur" },
        ]
      },
      queryTypeOptions: [
        { key: "productCode", display_name: "产品型号" },
        { key: "productName", display_name: "产品名称" },
      ],
      material: [],
    };
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh](crud) {
      crud.params.productType = this.productType;
      return true;
    },
    // 新建 - 之前
    [CRUD.HOOK.beforeToAdd](crud, data) {
      this.crud.form.productType = this.productType;
      crudProductMaterial.notBindList().then((res) => {
        this.material = res;
      });
      return true;
    },
    // 编辑 - 之前
    [CRUD.HOOK.beforeToEdit](crud, data) {
      crudProductMaterial.notBindList({materialCode: this.crud.form.materialCode}).then((res) => {
        this.material = res;
      });
      //设置选中值
      this.setChangeValue(crud);
      return true;
    },
    // 提交 - 之后
    [CRUD.HOOK.afterSubmit](crud, data) {
      return true;
    },
    // 提交 - 之前
    [CRUD.HOOK.beforeSubmit](crud) {
      let lines = [];
      crud.form.lines.forEach(item =>{
        lines.push({
          modelCode : crud.form.productCode,
          lineCode: item[0],
          sectionCode: item[1]
        });
      })
      crud.form.productModelLines = lines;
      return true;
    },
    //关联产线
    concernLineChange(value){
      if(value && value.length > 0){
        const arrPath = [];
        const checkeds = this.$refs.concernLine.getCheckedNodes();
        if(checkeds && checkeds.length > 0){
          checkeds.forEach(item =>{
            if(item.level == 1){
              this.$message.error('只能选择工段！');
              item.checked =false;
              return ;
            }

            if(arrPath.indexOf(item.path[0]) == -1){
              arrPath.push(item.path[0]);
            } else{
              this.$message.error('相同产线只能选择一个工段！');
              item.checked =false;
            }
          })
        }
        return true;
      }
    },
    //加载产线模型
    async loadFactoryModel (level, pid) {
      const params = {
        modelType : level ,
        pid : pid
      };
     return await crudFactoryModel.list(params).then(res =>{
        let nodes = [];
        if(res){
          res.forEach(item =>{
            nodes.push({
              value: item.modelCode,
              label: item.modelName,
              leaf: level >= 2,
              id: item.id,
              type: item.modelType
            });
          })
        }
        return nodes;
      })
    },
    //设置选中值
    setChangeValue(crud){
      //获取产线关联关系
      crudProductModelLien.list({modelCode: crud.form.productCode}).then(res =>{
        if(res){
          const lines = [];
          res.forEach(item =>{
            let arr = new Array();
            arr.push(item.lineCode);
            arr.push(item.sectionCode);
            lines.push(arr)
          })
          crud.form.lines = lines;
        }
      })
    }
  },
  mounted() {
    const root = this.loadFactoryModel(2);
    const lines = [];
    root.then((result) => {
      if(result){
        result.forEach(item =>{
          const children = this.loadFactoryModel(3,item.id);
          children.then(chi =>{
            item.children = chi;
          })
          lines.push(item);
        })
      }
    })
    this.options = lines;
  }

};
</script>

<style scoped>
</style>
